﻿using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
using Shipeng.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using YNTK.Common.Const;
using YNTK.Common.Enum;
using YNTK.Common.Filter;
using YNTK.Data.MongoDB.Repositorie;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.LinqBuilder;
using YNTK.Mapster;
using YNTK.System.Entitys.Dto.Common;
using YNTK.System.Entitys.Dto.Staff;
using YNTK.System.Entitys.Permission;
using YNTK.System.Entitys.Staff;
using YNTK.System.Interfaces.Common;
using YNTK.System.Interfaces.Permission;
using YNTK.System.Interfaces.Resources;
using YNTK.System.Interfaces.Staff;

namespace YNTK.System.Service.Staff
{
    /// <summary>
    /// 员工意见服务的实现
    /// 版 本：V1.0.0.0
    /// 版 权：云南通科科技有限公司（https://www.yntkkj.com）
    /// 作 者：李仕鹏
    /// 日 期：2022.11.01
    /// </summary>
    [ApiDescriptionSettings(Tag = "员工意见", Name = "Staff", Order = 785)]
    [Route("api/[controller]")]
    public class StaffService: IStaffService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<EmployeeCommentsEntity> _repository;//员工意见仓储
        private readonly IMongoDBRepository<EmployeeCommentsEntity> _mongoDbRepository;//员工意见mongodb仓储
        private readonly ISqlSugarRepository<EmployeeCommentFilesEntity> _fileRepository;//员工意见相关附件仓储
        private readonly IMongoDBRepository<EmployeeCommentFilesEntity> _fileMongoDbRepository;//员工意见相关附件mongodb仓储

        private readonly ITkUsersService _tkUsersService;//用户服务
        private readonly IOrganizeService _organizeService;//组织服务
        private readonly IMechanismService _mechanismService;//机构服务
        private readonly IDictionaryService _dictionaryService;//字典服务
        private readonly IFileService _fileService;//文件服务
        private readonly ITkRoleService _tkRoleService;//角色服务
        private readonly HttpContext _httpContext;

        private readonly string _comments = "employee_comments";//mongodb中员工意见数据集名称
        private readonly string _files = "employee_commentfiles";//mongodb中员工意见相关附件数据集名称

        /// <summary>
        /// 构造方法依赖注入
        /// </summary>
        /// <param name="repository">员工意见仓储</param>
        /// <param name="mongoDbRepository">员工意见mongodb仓储</param>
        /// <param name="fileRepository">员工意见相关附件仓储</param>
        /// <param name="fileMongoDbRepository">员工意见相关附件mongodb仓储</param>
        /// <param name="tkUsersService">用户服务</param>
        /// <param name="organizeService">组织服务</param>
        /// <param name="mechanismService">机构服务</param>
        /// <param name="dictionaryService">字典服务</param>
        /// <param name="fileService">文件服务</param>
        /// <param name="tkRoleService">角色服务</param>
        public StaffService(ISqlSugarRepository<EmployeeCommentsEntity> repository,
            IMongoDBRepository<EmployeeCommentsEntity> mongoDbRepository,
            ISqlSugarRepository<EmployeeCommentFilesEntity> fileRepository,
            IMongoDBRepository<EmployeeCommentFilesEntity> fileMongoDbRepository,
            ITkUsersService tkUsersService, IOrganizeService organizeService,
            IMechanismService mechanismService, IDictionaryService dictionaryService,
            IFileService fileService, ITkRoleService tkRoleService)
        {
            _repository = repository;
            _mongoDbRepository = mongoDbRepository;
            _fileRepository = fileRepository;
            _fileMongoDbRepository = fileMongoDbRepository;
            _tkUsersService = tkUsersService;
            _organizeService = organizeService;
            _mechanismService = mechanismService;
            _dictionaryService = dictionaryService;
            _fileService = fileService;
            _tkRoleService = tkRoleService;
            _httpContext = App.HttpContext;
        }

        /// <summary>
        /// 分页获取员工意见数据
        /// </summary>
        /// <param name="query">查询员工意见请求模型</param>
        /// <returns></returns>
        [HttpPost("gets")]
        public async Task<TkPageResult<EmployeeCommentsListDto>> Gets([FromBody] QueryEmployeeCommentFilterRequestModel query)
        {
            try
            {
                var user = _httpContext.User.FindFirst(ClaimConst.CLAINM_USERID);
                string userId = user.Value;
                string organizeId = user.Subject.FindFirst(ClaimConst.ORGANIZEID).Value;
                string mechanismId = user.Subject.FindFirst(ClaimConst.MECHANISMID).Value;
                string roleId = user.Subject.FindFirst(ClaimConst.ROLEID).Value;
                //账号类型【0.平台运营人员 1.超级管理员 2.组织管理员 3.组织用户 4.第三方登录用户 5.游客用户】
                var authenticationType = user.Subject.FindFirst(ClaimConst.ACCOUNTTYPE).Value;

                #region 拼接查询条件
                Expression<Func<EmployeeCommentsEntity, bool>> where = m =>
                m.DeleteMark == null && m.OrganizeId== organizeId && 
               (m.CreatorUserId == userId ||
               (m.SharedScope == 0 && m.OrganizeId == organizeId && m.EnabledMark == 1) ||
               (m.SharedScope == 1 && m.MechanismId == mechanismId && m.EnabledMark == 1) ||
               (m.SharedScope == 2 && m.SharedScopeValue.Contains(roleId) && m.EnabledMark == 1) ||
               (m.SharedScope == 3 && m.SharedScopeValue.Contains(userId) && m.EnabledMark == 1));

                if (query.enabledMark == 1) where = where.And(m => m.EnabledMark == 1);
                if (query.enabledMark == 0) where = where.And(m => m.EnabledMark != 1);
                if (!string.IsNullOrWhiteSpace(query.organizeId))
                    where = where.And(m => m.OrganizeId == query.organizeId);
                if (!string.IsNullOrWhiteSpace(query.mechanismId))
                {
                    string queryMechanismId = await _mechanismService.GetIdAsync(query.mechanismId, organizeId);
                    where = where.And(m => m.MechanismId == queryMechanismId);
                }
                if (!string.IsNullOrWhiteSpace(query.classifyId))
                {
                    string queryClassifyId = await _dictionaryService.GetIdAsync(query.classifyId, organizeId);
                    where = where.And(m => m.ClassifyId == queryClassifyId);
                }
                if (query.sharedScope != null)
                    where = where.And(m => m.SharedScope == query.sharedScope.GetHashCode());
                if (query.startTime != null) where = where.And(m => m.CreatorTime >= query.startTime);
                if (query.endTime != null) where = where.And(m => m.CreatorTime <= query.endTime);
                if (!string.IsNullOrWhiteSpace(query.keyword))
                    where = where.And(m => m.Title.Contains(query.keyword));
                #endregion

                var pageList = new SqlSugarPagedList<EmployeeCommentsListDto>();

                #region 先从mongodb中获取员工意见数据
                //排序生成器
                var builderSort = Builders<EmployeeCommentsEntity>.Sort;
                //排序约束   Ascending 正序    Descending 倒序
                var sort = builderSort.Descending(r => r.CreatorTime);
                //Item1.结果集 Item2.总条数 Item3.总页数
                (List<EmployeeCommentsEntity>, int, int) result =
                    await _mongoDbRepository.GetListAsync(_comments,
                    where, query.currentPage, query.pageSize, null, sort);
                pageList.list = result.Item1.Adapt<List<EmployeeCommentsListDto>>();
                pageList.pagination = new PagedModel()
                {
                    PageIndex = query.currentPage,
                    PageSize = query.pageSize,
                    Total = result.Item2,
                    PageCount = result.Item3
                };
                #endregion

                if (!pageList.list.Any())
                {
                    #region 再从sqlserver中获取工作记录数据
                    var sqlResult = await _repository.Entities.Where(where)
                        .OrderBy(r => r.CreatorTime, OrderByType.Desc)
                        .ToPagedListAsync(query.currentPage, query.pageSize);
                    pageList.list = sqlResult.list.Adapt<List<EmployeeCommentsListDto>>();
                    pageList.pagination = sqlResult.pagination;
                    #endregion
                }

                #region 处理员工意见返回数据
                if (pageList.list.Any())
                {
                    var orgIds = pageList.list.Select(r => r.organizeId).Distinct().ToList();
                    var orgs = await _organizeService.GetOrganizeListByIds(orgIds);
                    var mechanismIds = pageList.list.Where(r => !string.IsNullOrWhiteSpace(r.mechanismId))
                        ?.Select(r => r.mechanismId.Split(',').ToList())
                        ?.SelectMany(r => r).Distinct().ToList();
                    var mechanisms = !mechanismIds.Any() ? new List<MechanismEntity>() :
                        await _mechanismService.GetMechanismListAsync(null, mechanismIds);
                    var classifyIds = pageList.list.Select(r => r.classifyId.Split(',').ToList())
                       .SelectMany(r => r).Distinct().ToList();
                    var classifys = await _dictionaryService.GetDictionaryListByIds(classifyIds);
                    var userIds = pageList.list.Select(r => r.creatorUserId).Distinct().ToList();
                    var users = await _tkUsersService.GetUserListByIds(userIds);
                    pageList.list.ForEach(comment =>
                    {
                        comment.sharedScopeText = EnumHelper.GetEnumDescriptionString
                        (comment.sharedScope, typeof(SharedScopeEnum));
                        if (!string.IsNullOrWhiteSpace(comment.organizeId))
                            comment.organizeName = orgs?.FirstOrDefault(r => r.Id == comment.organizeId)?.FullName;
                        if (!string.IsNullOrWhiteSpace(comment.mechanismId))
                        {
                            comment.mechanismName = string.Join('/', mechanisms
                                ?.Where(r => comment.mechanismId.Split(',').ToList().Contains(r.Id))
                                ?.Select(r => r.Name)?.ToList());
                        }
                        if (!string.IsNullOrWhiteSpace(comment.classifyId))
                        {
                            comment.classifyName = string.Join('/', classifys
                                ?.Where(r => comment.classifyId.Split(',').ToList().Contains(r.Id))
                                ?.Select(r => r.Name)?.ToList());
                        }
                        comment.creatorUserName = users?.FirstOrDefault(r => r.Id == comment.creatorUserId)?.RealName;
                    });
                }
                #endregion

                return TkPageResult<EmployeeCommentsListDto>.Success(pageList);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("[")) throw YNTKException.Oh($"{ex.Message}");
                throw YNTKException.Oh($"分页获取员工意见数据发生异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取员工意见详细信息
        /// </summary>
        /// <param name="id">员工意见id</param>
        /// <returns></returns>
        [HttpGet("get/{id}")]
        public async Task<TkResult<EmployeeCommentsDto>> Get([Required] string id)
        {
            try
            {
                var entity = await GetEmployeeCommentInfoAsync(r => r.Id == id && r.DeleteMark == null);
                _ = entity ?? throw YNTKException.Oh(ErrorCode.Comment0003);

                var comment = entity.Adapt<EmployeeCommentsDto>();

                #region 处理员工意见返回信息
                comment.sharedScopeText = EnumHelper.GetEnumDescriptionString
                        (comment.sharedScope, typeof(SharedScopeEnum));
                if (!string.IsNullOrWhiteSpace(comment.organizeId) && comment.organizeId != "org00000000")
                    comment.organizeName = (await _organizeService.GetOrganizeListByIds
                            (new List<string>() { comment.organizeId }))?[0].FullName;
                if (!string.IsNullOrWhiteSpace(comment.mechanismId) && comment.mechanismId != "jg000000")
                {
                    comment.mechanismName = string.Join('/', (await _mechanismService
                        .GetMechanismListAsync(null, comment.mechanismId.Split(',').ToList()))
                        ?.Select(r => r.Name)?.ToList());
                }
                if (!string.IsNullOrWhiteSpace(comment.classifyId))
                {
                    comment.classifyName = string.Join('/', (await _dictionaryService
                   .GetDictionaryListByIds(comment.classifyId.Split(',').ToList()))
                   ?.Select(r => r.Name)?.ToList());
                }
                #region 处理共享范围
                if (!string.IsNullOrWhiteSpace(comment.sharedScopeValue))
                {
                    //共享范围(0.全组织 1.特定机构 2.特定角色 3.特定用户 4.仅自己可见)
                    switch (comment.sharedScope)
                    {
                        case 0:
                            comment.sharedScopeValueText = "全组织";
                            break;
                        case 1:
                            var dic = await _mechanismService.GetIdsAsync(comment.sharedScopeValue.Split(',').ToList(), comment.organizeId);
                            var values = dic.Values.ToList();
                            comment.sharedScopeValueText = string.Join(',', values.Select(r => r.Item2).ToList());
                            comment.sharedScopeMechanismValue = values.Select(r => r.Item1.Split(',').ToArray())?.ToList();
                            break;
                        case 2:
                            comment.sharedScopeValueText = string.Join(',', (await _tkRoleService
                                .GetTkRoleListByIdsAsync(comment.sharedScopeValue.Split(',').ToList()))
                                ?.Select(r => r.Name)?.ToList());
                            break;
                        case 3:
                            comment.sharedScopeValueText = string.Join(',', (await _tkUsersService
                               .GetUserListByIds(comment.sharedScopeValue.Split(',').ToList()))
                               ?.Select(r => r.RealName)?.ToList());
                            break;
                        case 4:
                            comment.sharedScopeValueText = "仅自己可见";
                            break;
                    }
                }
                #endregion
                if (!string.IsNullOrWhiteSpace(comment.creatorUserId))
                    comment.creatorUserName = (await _tkUsersService.GetUserInfoByUserId(comment.creatorUserId))?.RealName;
                #endregion

                //获取员工意见相关附件数据
                var fileData = await GetEmployeeCommentFilesListAsync(id);
                comment.fileData = fileData.Adapt<List<CommonFileListDto>>();

                #region 累加浏览次数
                entity.ViewCount++;
                await _repository.Context.Updateable(entity)
                    .IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await _mongoDbRepository.UpdateAsync(entity, _comments, m => m.Id == entity.Id);
                #endregion

                return TkResult<EmployeeCommentsDto>.Success(comment);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("[")) throw YNTKException.Oh($"{ex.Message}");
                throw YNTKException.Oh($"获取员工意见详细信息发生异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 添加员工意见信息
        /// </summary>
        /// <param name="input">添加员工意见请求模型</param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add([FromBody] AddEmployeeCommentRequestModle input)
        {
            try
            {
                var user = _httpContext.User.FindFirst(ClaimConst.CLAINM_USERID);
                string userId = user.Value;
                string organizeId = user.Subject.FindFirst(ClaimConst.ORGANIZEID).Value;
                string mechanismId = user.Subject.FindFirst(ClaimConst.MECHANISMID).Value;
                //账号类型【0.平台运营人员 1.超级管理员 2.组织管理员 3.组织用户 4.第三方登录用户 5.游客用户】
                var authenticationType = user.Subject.FindFirst(ClaimConst.ACCOUNTTYPE).Value;
                if (authenticationType == "4" || authenticationType == "5")
                    throw YNTKException.Oh(ErrorCode.D1016);

                if ((await GetEmployeeCommentInfoAsync(r => r.OrganizeId == organizeId &&
                r.MechanismId == mechanismId && r.ClassifyId == input.classifyId 
                && r.Title == input.title && r.CreatorUserId!=userId && r.DeleteMark == null)) != null)
                    throw YNTKException.Oh(ErrorCode.Comment0004);

                var entity = input.Adapt<EmployeeCommentsEntity>();
                entity.SharedScope = input.sharedScope.GetHashCode();
                entity.OrganizeId = organizeId;
                entity.MechanismId = mechanismId;

                //保存员工意见到sqlserver
                var isOk = await _repository.Context.Insertable(entity)
                   .CallEntityMethod(m => m.Creator()).ExecuteReturnEntityAsync();
                _ = isOk ?? throw YNTKException.Oh(ErrorCode.Comment0005);

                //保存员工意见到mongodb
                entity = isOk;
                var result = await _mongoDbRepository.AddAsync(entity, _comments);
                if (!result) throw YNTKException.Oh(ErrorCode.Comment0006);

                //保存员工意见相关附件
                await SaveEmployeeCommentFilesAsync(entity, input.fileData);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("[")) throw YNTKException.Oh($"{ex.Message}");
                throw YNTKException.Oh($"添加员工意见信息发生异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 修改员工意见信息
        /// </summary>
        /// <param name="input">修改员工意见请求模型</param>
        /// <returns></returns>
        [HttpPut("update")]
        public async Task Update([FromBody] UpdateEmployeeCommentRequestModle input)
        {
            try
            {
                var user = _httpContext.User.FindFirst(ClaimConst.CLAINM_USERID);
                string userId = user.Value;
                string organizeId = user.Subject.FindFirst(ClaimConst.ORGANIZEID).Value;
                string mechanismId = user.Subject.FindFirst(ClaimConst.MECHANISMID).Value;
                //账号类型【0.平台运营人员 1.超级管理员 2.组织管理员 3.组织用户 4.第三方登录用户 5.游客用户】
                var authenticationType = user.Subject.FindFirst(ClaimConst.ACCOUNTTYPE).Value;
                if (authenticationType == "4" || authenticationType == "5")
                    throw YNTKException.Oh(ErrorCode.D1016);

                var entity = await GetEmployeeCommentInfoAsync(r => r.Id == input.id && r.DeleteMark == null);
                _ = entity ?? throw YNTKException.Oh(ErrorCode.Comment0003);
                if (entity.CreatorUserId != userId) throw YNTKException.Oh(ErrorCode.D1016);
                if ((await GetEmployeeCommentInfoAsync(r => r.OrganizeId == organizeId &&
               r.MechanismId == mechanismId && r.ClassifyId == input.classifyId
               && r.Title == input.title && r.CreatorUserId != userId && r.Id!=input.id && r.DeleteMark == null)) != null)
                    throw YNTKException.Oh(ErrorCode.Comment0004);

                entity = input.Mapper(entity);
                entity.SharedScope = input.sharedScope.GetHashCode();
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyUserId = userId;

                //保存员工意见到sqlserver
                var isOK = await _repository.Context.Updateable(entity)
               .IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                if (!(isOK > 0)) throw YNTKException.Oh(ErrorCode.Comment0007);

                //保存员工意见到mongodb
                var update = await _mongoDbRepository.UpdateAsync(entity, _comments, m => m.Id == entity.Id);
                if (!(update.ModifiedCount > 0)) throw YNTKException.Oh(ErrorCode.Comment0008);

                //保存员工意见相关附件
                await SaveEmployeeCommentFilesAsync(entity, input.fileData);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("[")) throw YNTKException.Oh($"{ex.Message}");
                throw YNTKException.Oh($"修改员工意见信息发生异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除员工意见
        /// </summary>
        /// <param name="id">员工意见id</param>
        /// <returns></returns>
        [HttpDelete("delete/{id}")]
        public async Task Delete([Required] string id)
        {
            try
            {
                var user = _httpContext.User.FindFirst(ClaimConst.CLAINM_USERID);
                string userId = user.Value;
                //账号类型【0.平台运营人员 1.超级管理员 2.组织管理员 3.组织用户 4.第三方登录用户 5.游客用户】
                var authenticationType = user.Subject.FindFirst(ClaimConst.ACCOUNTTYPE).Value;
                if (authenticationType == "4" || authenticationType == "5")
                    throw YNTKException.Oh(ErrorCode.D1016);

                var entity = await GetEmployeeCommentInfoAsync(r => r.Id == id && r.DeleteMark == null);
                _ = entity ?? throw YNTKException.Oh(ErrorCode.Comment0003);
                if (entity.CreatorUserId != userId) throw YNTKException.Oh(ErrorCode.D1016);

                //从sqlserver中删除
                var isOk = await _repository.Context.Deleteable(entity).ExecuteCommandAsync();
                if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.Comment0009);

                //从mongodb中删除
                var delete = await _mongoDbRepository.DeleteAsync(_comments, m => m.Id == id);
                if (!(delete > 0)) throw YNTKException.Oh(ErrorCode.Comment0010);

                //删除员工意见相关附件
                await DeleteEmployeeCommentFilesAsync(id);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("[")) throw YNTKException.Oh($"{ex.Message}");
                throw YNTKException.Oh($"删除员工意见信息发生异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 更新员工意见状态(启用/禁用)
        /// </summary>
        /// <param name="id">员工意见id</param>
        /// <returns></returns>
        [HttpPut("state/{id}")]
        public async Task UpdateState([Required] string id)
        {
            try
            {
                var user = _httpContext.User.FindFirst(ClaimConst.CLAINM_USERID);
                string userId = user.Value;
                //账号类型【0.平台运营人员 1.超级管理员 2.组织管理员 3.组织用户 4.第三方登录用户 5.游客用户】
                var authenticationType = user.Subject.FindFirst(ClaimConst.ACCOUNTTYPE).Value;
                if (authenticationType == "4" || authenticationType == "5")
                    throw YNTKException.Oh(ErrorCode.D1016);

                var entity = await GetEmployeeCommentInfoAsync(r => r.Id == id && r.DeleteMark == null);
                _ = entity ?? throw YNTKException.Oh(ErrorCode.Comment0003);
                if (entity.CreatorUserId != userId) throw YNTKException.Oh(ErrorCode.D1016);

                //sqlserver更新员工意见状态
                var isOk = await _repository.Context.Updateable<EmployeeCommentsEntity>()
               .SetColumns(it => new EmployeeCommentsEntity()
               {
                   EnabledMark = SqlFunc.IIF(it.EnabledMark == 1, 0, 1),
                   LastModifyUserId = userId,
                   LastModifyTime = SqlFunc.GetDate()
               }).Where(it => it.Id == id).ExecuteCommandAsync();
                if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.Comment0011);

                //mongodb更新员工意见状态
                entity.EnabledMark = entity.EnabledMark == 1 ? 0 : 1;
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyUserId = userId;
                var update = await _mongoDbRepository.UpdateAsync(entity, _comments, m => m.Id == entity.Id);
                if (!(update.ModifiedCount > 0)) throw YNTKException.Oh(ErrorCode.Comment0012);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("[")) throw YNTKException.Oh($"{ex.Message}");
                throw YNTKException.Oh($"更新员工意见状态(启用/禁用)发生异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 根据条件获取员工意见信息
        /// </summary>
        /// <param name="where">条件</param>
        /// <returns></returns>
        private async Task<EmployeeCommentsEntity> GetEmployeeCommentInfoAsync(Expression<Func<EmployeeCommentsEntity, bool>> where)
        {
            //从从mongodb中获取
            var entity = await _mongoDbRepository.GetAsync(_comments, where);
            //再从sqlserver中获取
            if (entity == null) entity = await _repository.FirstOrDefaultAsync(where);
            return entity;
        }

        #region 工作记录相关附件
        /// <summary>
        /// 获取员工意见相关附件数据
        /// </summary>
        /// <param name="commentId">员工意见id</param>
        /// <returns></returns>
        private async Task<List<EmployeeCommentFilesEntity>> GetEmployeeCommentFilesListAsync(string commentId)
        {
            //从mongodb中获取附件数据
            var result = await _fileMongoDbRepository.GetListAsync(_files, r => r.CommentId  == commentId);
            if (!result.Any())
            {
                //从sqlserver数据库中获取附件数据
                result = await _fileRepository.Entities
                    .Where(r => r.CommentId == commentId).ToListAsync();
            }
            return result;
        }

        /// <summary>
        /// 保存员工意见相关附件
        /// </summary>
        /// <param name="entity">员工意见信息</param>
        /// <param name="fileData">附件数据</param>
        /// <returns></returns>
        private async Task SaveEmployeeCommentFilesAsync(EmployeeCommentsEntity entity, List<CommonFileRequestModel> fileData)
        {
            try
            {
                _fileRepository.Ado.BeginTran();
                //删除原数据
                await _fileMongoDbRepository.DeleteAsync(_files, r => r.CommentId == entity.Id);
                await _fileRepository.DeleteAsync(r => r.CommentId == entity.Id);
                if (fileData != null && fileData.Count > 0)
                {
                    var files = new List<EmployeeCommentFilesEntity>();
                    var file = new EmployeeCommentFilesEntity();
                    fileData.ForEach(item =>
                    {
                        file = item.Adapt<EmployeeCommentFilesEntity>();
                        file.Id = YitIdHelper.NextId().ToString();
                        file.OrganizeId = entity.OrganizeId;
                        file.MechanismId = entity.MechanismId;
                        file.CommentId = entity.Id;
                        file.CreatorUserId = entity.CreatorUserId;
                        file.CreatorTime = entity.CreatorTime;
                        files.Add(file);
                    });
                    //保存到sqlserver                 
                    var isOk = await _fileRepository.Context.Insertable(files).ExecuteCommandAsync();
                    if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.Comment0001);
                    //保存到mongodb
                    var succeed = await _fileMongoDbRepository.AddListAsync(files, _files);
                    if (!succeed) throw YNTKException.Oh(ErrorCode.Comment0002);
                }
                _fileRepository.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                _fileRepository.Ado.RollbackTran();
                if (ex.Message.Contains("[")) throw YNTKException.Oh($"{ex.Message}");
                throw YNTKException.Oh($"保存工作记录相关附件发生异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除员工意见相关附件数据
        /// </summary>
        /// <param name="commentId">员工意见id</param>
        /// <returns></returns>
        private async Task DeleteEmployeeCommentFilesAsync(string commentId)
        {
            var result = await GetEmployeeCommentFilesListAsync(commentId);
            if (result.Any())
            {
                //删除原数据
                await _fileMongoDbRepository.DeleteAsync(_files, r => r.CommentId == commentId);
                await _fileRepository.DeleteAsync(r => r.CommentId == commentId);
                //删除文件
                var deleteFiles = result.Adapt<List<FileListDto>>();
                _fileService.DeleteFiles(deleteFiles);
            }
        }
        #endregion

    }
}
